<?php

$maintenance = 0;
if ($maintenance) {
    include "View/Master/MaintenanceHTML.php";
    return;
}
$items = array();
$itemTotal = 0;
header('Content-type: text/html; charset=utf-8');
ob_start(); //Begin traking data
//Param parser
#remove the directory path we don't want 
$url = $_SERVER['REQUEST_URI'];
$url = ltrim($url, '/');
$request = $url;
if (strpos($request, '?') != '') {
    $request = substr($request, 0, strpos($request, "?"));
}
#split the path by '/'
$params = array($request);
if (strpos($request, '/'))
$params = split("/", $request);

$userSwitchedFrom = null;
session_start();
if (isset($_SESSION['switchfrom']))
    $userSwitchedFrom = $_SESSION['switchfrom'];
$userId = null;
if (isset($_SESSION['userid']))
$userId = $_SESSION['userid'];
if (strtoupper($params[0]) !== 'AUTHORIZEFACEBOOK')
    session_write_close();

//detect device
include("Libs/mobiledetect/Mobile_Detect.php");
$detect = new Mobile_Detect;
global $deviceType;
$deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'Tablet' : 'Mobile') : 'Desktop');

//Load all php file
include("ClassLoader/Loader.php");
$loader = new Loader();
$loader->load();
if (isset($userId))
    $user = User::withId($userId);
$streamId = 1;

if (!$userId && strtoupper($params[0]) != "M" && strtoupper($params[0]) != "WS")
    $params[0] = 'LOGIN';

switch (strtoupper($params[0])) {
    case "USER":
        if (strtoupper($params[1]) == 'LOGIN')
            $params[0] = "USERLOGIN";
        $pageTitle = "Login to buzzPulse";
        break;
    case "PAGE":
        break;
    case "M":
        //$soapRequest = $_REQUEST['request'];
        //$server = new bpServer("/m/");
        $server = new mineServer("/m/");

        $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
        //$server->service($HTTP_RAW_POST_DATA);
        $server->service();
        return;
        break;
    case "HOME":
        $pageTitle = "Welcome to buzzPulse";
        break;
    case "STREAM":
        if ($params[1] != '')
            $streamId = ($params[1]);
        $stream = Stream::withId($streamId);
        $userCreated = User::withId($stream->userId);
        $currentUser = User::withId($userId);

        $streamView = new StreamView();
        $streamController = new StreamController($stream, $streamView);
        $dateTo = new DateTime();
        $dateFrom = new DateTime();
        $dateFrom->sub(new DateInterval("P10D"));
        $pageTitle = "Stream for " . $stream->name;
        $streamController->render($dateFrom->format("d-m-Y H:i:s"), $dateTo->format("d-m-Y H:i:s"), 0, 10);
        if ($params[2])
            $params[1] = $params[2];
        $params[0] = "STREAM";
        break;
    case "ALERT":
        if ($params[1] != '')
            $streamId = ($params[1]);
        $stream = Stream::withId($streamId);
        $userCreated = User::withId($stream->userId);
        $currentUser = User::withId($_SESSION["userid"]);
        $streamView = new StreamView();
        $streamController = new StreamController($stream, $streamView);
        $dateTo = new DateTime();
        $dateFrom = new DateTime();
        $dateFrom->sub(new DateInterval("P10D"));
        $pageTitle = "Signal for " . $stream->name;
        $streamController->renderSignals($dateFrom->format("d-m-Y H:i:s"), $dateTo->format("d-m-Y H:i:s"));
        if ($params[2])
            $params[1] = $params[2];
        break;
    case "METRICS":
        if ($params[1] != '')
            $streamId = $params[1];
        $stream = Stream::withId($streamId);
        $userCreated = User::withId($stream->userId);
        $currentUser = User::getLogedInUser();
        $language = '';
        $location = '';
        $platform = '';
        $tags = '';
        $sentiment = '';
        $gender = '';
        $reach = '';
        $dateTo = new DateTime();
        $dateFrom = new DateTime();
        $dateFrom->sub(new DateInterval("P10D"));
        $filter = array("streamId" => $streamId, "dateFrom" => $dateFrom->format("d-m-Y"), "dateTo" => $dateTo->format("d-m-Y"), "language" => $language,
            "location" => $location, "platform" => $platform, "tag" => $tags, "sentiment" => $sentiment,
            "gender" => $gender, "reach" => $reach);
        $metricsController = new MetricsController(new Metrics(), new MetricsView());
        $metricsController->render($filter);
        if ($params[2])
            $params[1] = $params[2];
        $params[0] = "METRICS";
        $pageTitle = "Metrics for " . $stream->name;
        break;
    case "COMPARE":
        if ($params[1] != '')
            $streamId = $params[1];
        if ($params[2])
            $params[1] = $params[2];
        $params[0] = "COMPARE";
        $dateTo = new DateTime();
        $dateFrom = new DateTime();
        $dateFrom->sub(new DateInterval("P10D"));
        $pageTitle = "Comparision for " . $stream->name;
        $compareColtroller = new CompareController(new stdClass(), new stdClass());
        $filter = array("streamId" => $streamId, "dateFrom" => $dateFrom->format("d-m-Y"), "dateTo" => $dateTo->format("d-m-Y"), "language" => $language,
            "location" => $location, "platform" => $platform, "tag" => $tags, "sentiment" => $sentiment,
            "gender" => $gender, "reach" => $reach);
        $compareColtroller->render($filter);
        break;
    case "ENGAGEMENT":
        if ($params[1] != '')
            $streamId = $params[1];
        if ($params[2])
            $params[1] = $params[2];
        $params[0] = "ENGAGEMENT";
        $dateTo = new DateTime();
        $dateFrom = new DateTime();
        $dateFrom->sub(new DateInterval("P10D"));
        $pageTitle = "Engagement for " . $stream->name;
        $engagementController = new EngagementController(new stdClass(), new stdClass());
        $filter = array("streamId" => $streamId, "dateFrom" => $dateFrom->format("d-m-Y"), "dateTo" => $dateTo->format("d-m-Y"), "language" => $language,
            "location" => $location, "platform" => $platform, "tag" => $tags, "sentiment" => $sentiment,
            "gender" => $gender, "reach" => $reach);
        $engagementController->render($filter);
        break;
    case "SENTIMENT":
        if ($params[1] != '')
            $streamId = ($params[1]);
        $stream = Stream::withId($streamId);
        $userCreated = User::withId($stream->userId);
        $currentUser = User::withId($userId);

        $streamView = new StreamView();
        $streamController = new StreamController($stream, $streamView);
        $dateTo = new DateTime();
        $dateFrom = new DateTime();
        $dateFrom->sub(new DateInterval("P10D"));
        $pageTitle = "Sentiment Scoring for " . $stream->name;
        $streamController->render($dateFrom->format("d-m-Y H:i:s"), $dateTo->format("d-m-Y H:i:s"), 0, 10);
        if ($params[2])
            $params[1] = $params[2];
        $params[0] = "SENTIMENT";
        break;
    case "ACTIVITY":
        $taskController = new TaskController(new Task(), new TaskView());
        $taskController->render();
        $pageTitle = "Activitiy";
        break;
    case "REPORT":

        break;
    case "AJAX":
        if (file_exists("View/".$deviceType."/AJAX/$params[1]HTML.php"))
            include "View/".$deviceType."/AJAX/$params[1]HTML.php";
        header('Content-length: ' . ob_get_length());
        return;
        break;
    case "":
        $params[0] = "Home";
        break;
    case "INFO":
        if ($params[3] != 'undefined') {
            $dateTo = DateTime::createFromFormat("d-m-Y", urldecode($params[3]));
            $dateFrom = DateTime::createFromFormat("d-m-Y", urldecode($params[2]));
        } else {
            $dateTo = new DateTime();
            $dateFrom = new DateTime();
            $dateFrom->sub(new DateInterval("P10D"));
        }
        $language = $params[6];
        $location = 0;
        $platform = 0;
        $tags = $params[7];
        $sentiment = $params[8];
        $type = $params[9];
        $gender = 0;
        $reach = 0;
        $index = $params[4];
        if ($index == "")
            $index = 10 * ($page - 1);
        $length = $params[5];

        $length = 10;
        //Message action parser
        $messageAction = '';
        if (isset($_REQUEST['filter'])) {
            if (strpos($_REQUEST['filter'], '/')) {
                $filters = explode('/', $_REQUEST['filter']);
                $_REQUEST['filter'] = $filters[0];
            }
            $messageAction = $_REQUEST['filter'];
        }
        mineServer::loadStream($params[1], $dateFrom->format("d-m-Y H:i:s"), $dateTo->format("d-m-Y H:i:s"), $language, $location, $platform, $tags, $sentiment, $gender, $reach, $index, $length, $messageAction, $type);
        header('Content-length: ' . ob_get_length());
        return;
        break;
    case "LOADSTREAM":
        if ($params[3] != 'undefined') {
            $dateTo = DateTime::createFromFormat("d-m-Y", urldecode($params[3]));
            $dateFrom = DateTime::createFromFormat("d-m-Y", urldecode($params[2]));
        } else {
            $dateTo = new DateTime();
            $dateFrom = new DateTime();
            $dateFrom->sub(new DateInterval("P10D"));
        }
        $language = $params[6];
        $location = 0;
        $platform = 0;
        $tags = explode(',', $params[7]);
        $sentiment = $params[8];
        $type = explode(',', $params[9]);
        $gender = 0;
        $reach = 0;
        $index = $params[4];
        if ($index == "")
            $index = 10 * ($page - 1);
        $length = $params[5];
        $source = explode(',', $params[10]);
        //Message action parser
        $messageAction = '';
        $actionData = array();
        if (isset($_REQUEST['filter']))
            $actionData = explode('/', $_REQUEST['filter']);
        $messageAction = $actionData[0];
        mineServer::loadStream($params[1], $dateFrom->format("d-m-Y H:i:s"), $dateTo->format("d-m-Y H:i:s"), $language, $location, $platform, $tags, $sentiment, $gender, $reach, $index, $length, $messageAction, $type, $source);
        header('Content-length: ' . ob_get_length());
        return;
    case "LOADSENTIMENTSTREAM":
        if ($params[3] != 'undefined') {
            $dateTo = DateTime::createFromFormat("d-m-Y", urldecode($params[3]));
            $dateFrom = DateTime::createFromFormat("d-m-Y", urldecode($params[2]));
        } else {
            $dateTo = new DateTime();
            $dateFrom = new DateTime();
            $dateFrom->sub(new DateInterval("P10D"));
        }
        $language = $params[6];
        $location = 0;
        $platform = 0;
        $tags = $params[7];
        $sentiment = $params[8];
        $type = $params[9];
        $source = $params[10];
        $gender = 0;
        $reach = 0;
        $index = $params[4];
        if ($index == "")
            $index = 10 * ($page - 1);
        $length = $params[5];

        //Message action parser
        $messageAction = '';
        $actionData = array();
        if (isset($_REQUEST['filter']))
            $actionData = explode('/', $_REQUEST['filter']);
        $messageAction = $actionData[0];
        $stream = Stream::withId($params[1]);
        $sourceQuery = '';
        if ($source != '0')
            $sourceQuery = ' & @source "' . urldecode($source) . '" ';
        $thread = '';
        if (isset($_REQUEST['threadId'])) {
            $thread = $_REQUEST['threadId'];
        }

        $threadSQL = '';
        if ($thread != '')
            $threadSQL = 'AND threadid = ' . $thread;

        $undefinedFilter = false;
        $excludeMessages = array();
        if ($_REQUEST['undefined']) {
            $undefinedFilter = true;
            $dateF = $dateFrom->format('Y-m-d');
            $dateT = $dateTo->format('Y-m-d');
            $msgQuery = "SELECT messageid FROM sentimentdata WHERE datecreated >= '$dateF 00:00:00' AND datecreated <= '$dateT 23:59:59' AND streamid=$stream->streamId $threadSQL";
            $result = Database::getInstance()->query($msgQuery);
            if ($result->returnCode == 200) {
                if ($result->dataTable->numOfRow > 0) {
                    $rows = $result->dataTable->rows;
                    foreach ($rows as $row) {
                        $excludeMessages[] = 0 + $row[0];
                    }
                }
            }
        }
        if ($thread == '') {
            if ($tags == 0 && $sentiment == 0) {
                $spamQuery = SpamMessages::getQuery($stream->streamId);
                $reader = new ZPulseReader($dateFrom->format("d-m-Y"), $dateTo->format("d-m-Y"), 7, '(' . $stream->query . $spamQuery . ')' . $sourceQuery, $language, $platform);
                $items = array();
                if ($platform == 0)
                    $reader = new ZPulseReader($dateFrom->format("d-m-Y"), $dateTo->format("d-m-Y"), 7, '(' . $stream->query . $spamQuery . ')' . $sourceQuery, $language);
                try {
                    $reader->read(function($item, $replies, $total) use (&$items, $thread, $params) {
                        $item->totalReplies = $replies;
                        $items[] = $item;
                        if ($item->getLead() !== $item->getText() && $thread == '')
                            return;
                        include "View/".$deviceType."/Post/SimplePost1.php";
                        echo ' |||||| ';
                        ob_flush();
                        flush();
                    }, $index, $length);
                } catch (Exception $e) {
                    echo $e->getMessage();
                }
            } else {
                $items = Stream::getPulse($stream->streamId, $dateFrom->format("d-m-Y"), $dateTo->format("d-m-Y"), $index, $length, $source, $type, $tags);
                if (is_array($items))
                    foreach ($items as $item) {
                        include "View/".$deviceType."/Post/SimplePost1.php";
                        echo ' |||||| ';
                        ob_flush();
                        flush();
                }
                return;
            }
            return;
        } else {
            if ($thread !== 'u') {
                if ($tags == 0 && $sentiment == 0) {
                    $spamQuery = SpamMessages::getQuery($stream->streamId);
                    $reader = new ZMessageReader($dateFrom->format("d-m-Y"), $dateTo->format("d-m-Y"), 7, '(' . $stream->query . $spamQuery . ')' . $sourceQuery, $language, $platform);
                    if ($platform == 0)
                        $reader = new ZMessageReader($dateFrom->format("d-m-Y"), $dateTo->format("d-m-Y"), 7, '(' . $stream->query . $spamQuery . ')' . $sourceQuery, $language);
                    $reader->setExcludedIds($excludeMessages);
                    $reader->filterByThread($thread);
                    try {
                                $reader->read(function($item, $total) use (&$items, $thread, $params) {
                                    include "View/".$deviceType."/Post/SimplePost1.php";
                            echo ' |||||| ';
                            ob_flush();
                            flush();
                        }, $index, $length);
                    } catch (Exception $e) {
                        echo $e->getMessage();
                    }
                    //header('Content-length: ' . ob_get_length());
                    return;
                } else {
                    $items = Stream::getMessages($stream->streamId, $dateFrom->format("d-m-Y"), $dateTo->format("d-m-Y"), $tags, $sentiment, $source, $index, $length, $thread);
                    if (is_array($items))
                        foreach ($items as $item) {
                            include "View/".$deviceType."/Post/SimplePost1.php";
                            echo ' |||||| ';
                            ob_flush();
                            flush();
                        }
                    return;
                }
            } else {
                $spamQuery = SpamMessages::getQuery($stream->streamId);
                $reader = new ZMessageReader($dateFrom->format("d-m-Y"), $dateTo->format("d-m-Y"), 7, '(' . $stream->query . $spamQuery . ')' . $sourceQuery, $language, $platform);
                if ($platform == 0)
                    $reader = new ZMessageReader($dateFrom->format("d-m-Y"), $dateTo->format("d-m-Y"), 7, '(' . $stream->query . $spamQuery . ')' . $sourceQuery, $language);
                $reader->setExcludedIds($excludeMessages);
                $reader->filterByThread($thread);
                try {
                    $reader->read(function($item, $total) use (&$items, $thread, $params) {
                        include "View/".$deviceType."/Post/SimplePost1.php";
                        echo ' |||||| ';
                        ob_flush();
                        flush();
                    }, $index, $length);
                } catch (Exception $e) {
                    echo $e->getMessage();
                }
                return;
            }
        }
        return;
        break;
    case "NEWSTREAM":
        $dateTo = new DateTime();
        $dateFrom = new DateTime(urldecode($params[2]));
        $language = 2;
        $location = 0;
        $platform = 0;
        $tags = "";
        $sentiment = 0;
        $gender = 0;
        $reach = 0;
        $index = 0;
        $length = 10;
        try {
            mineServer::loadStream($params[1], $dateFrom->format("d-m-Y H:i:s"), $dateTo->format("d-m-Y H:i:s"), $language, $location, $platform, $tags, $sentiment, $gender, $reach, $index, $length);
        } catch (Exception $err) {
            
        }
        header('Content-length: ' . ob_get_length());
        return;
    case "LOADMETRICS":
        $dateTo = new DateTime(urldecode($params[3]));
        $dateFrom = new DateTime(urldecode($params[2]));
        mineServer::loadMetrics($params[1], $dateFrom->format("d-m-Y H:i:s"), $dateTo->format("d-m-Y H:i:s"));
        header('Content-length: ' . ob_get_length());
        return;
        break;
    case "LOADTOPSOCIAL":
        $dateTo = new DateTime(urldecode($params[3]));
        $dateFrom = new DateTime(urldecode($params[2]));
        mineServer::loadTopSocial($params[1], $dateFrom->format("d-m-Y"), $dateTo->format("d-m-Y"));
        header('Content-length: ' . ob_get_length());
        return;
        break;
    case "LOGIN":
        $userView = UserView::getInstance();
        $userView->display("LoginViewHTML.php");
        $pageTitle = "Login to buzzPulse";
        break;
    case "SETTINGS":
        $params[0] = "Settings";
        $pageTitle = "buzzPulse Settings";
        break;
    case "IRRELEVANT":
        $url = ltrim($_SERVER['REQUEST_URI'], '/');
        $params = explode('/', $url);
        unset($params[0]);
        $streamId = base64_decode($params[1]);
        unset($params[1]);
        $url = implode('/', $params);
        $reader = new ZPostReader($url, 7);
        $threadId = 0;
        $totalMessages = 0;
        $collection = $reader->read(function($item, $total) use (&$threadId) {
            $threadId = $item->getThreadId();
        }, 0, 1);
        echo $threadId;
        $totalMessages = count($collection->getItems());
        $db = Database::getInstance();
        $query = "SELECT messageid FROM sentimentdata WHERE streamid = $streamId AND threadid = $threadId";
        $result = $db->query($query);
        $excludeMessages = array();
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow > 0) {
                foreach ($result->dataTable->rows as $row)
                    $excludeMessages[] = 0 + $row[0];
            }
        }
        $dateTo = new DateTime();
        $dateFrom = new DateTime();
        $dateFrom->sub(new DateInterval("P30D"));
        $stream = Stream::withId(base64_encode($streamId));
        $reader = new ZMessageReader($dateFrom->format('d-M-Y'), $dateTo->format('d-M-Y'), 7, $stream->query);
        $reader->filterByThread($threadId);
        $reader->setExcludedIds($excludeMessages);
        $userId = User::getCurrentUserId();
        echo 'System scored ' . count($excludeMessages) . '/' . $totalMessages . ' messages, ' . ($totalMessages - count($excludeMessages)) . ' messages left.<br>';
        $i = 0;
        $succeed = 0;
        try {
            $reader->read(function($item, $total) use (&$i, $userId, $streamId, $totalMessages, &$succeed) {
                if ($i == 0) {
                    echo 'Importing ' . $total . ' matched messages...<br>';
                    echo "<div id=\"progress\"></div>";
                }
                $messageId = $item->getId();
                $threadId = $item->getThreadId();
                $date = new DateTime($item->getTime());
                $sqlDate = $date->format('Y-m-d H:i:s');
                $type = $item->getType();
                $source = addslashes($item->getSource());
                $db = Database::getInstance();
                $result = $db->query("INSERT INTO sentimentdata (userid, messageid, threadid, score, datecreated, streamid, type, source, userscoring, edited) "
                        . "VALUES ($userId, $messageId, $threadId, -3, '$sqlDate', $streamId, $type, '$source', 1, 113);");
                if ($result->returnCode === 200) {
                    $succeed++;
                }
                //echo "UPDATE sentimentdata SET streamid=-16010 WHERE messageid=$messageId LIMIT 1;<br>";
                $i++;
                $percent = round($i / $total * 100);
                $failed = '';
                if ($succeed < $i)
                    $failed = '(' . ($i - $succeed) . ' failed)';
                echo "<script>progress.innerHTML = 'Proccessing... $i/$total completed $failed. ($percent%)'</script>";
                echo str_repeat("\0", 4096);
                ob_flush();
                flush();
            }, 0, 5000);
        } catch (Exception $err) {
            $message = $err->getMessage();
            if ($message == 'Your query has no result! Try again!')
                echo 'All message is scored as irrelevant!';
            else
                echo $err->getMessage();
        }
        exit();
    case "TEST":
        $debug = true;
        if (isset($_REQUEST['buzzpulse']))
            $debug = false;
        Mail::sendDigestEmail($debug);
        return;
        break;
    case "WS":
        $streamId = $params[2];
        $type = '';
        $query = '';
        if ($params[3]) {
        $_filter = (array) json_decode(urldecode($params[3]));
        $_filter['streamId'] = $streamId;
            $type = array('0');
            if (isset($_filter['type']))
                $type = $_filter['type'];
        $stream = Stream::withId($streamId);
        $query = $stream->query;
        }
        else {
            $_filter = (array) json_decode(urldecode($params[2]));
        }
        switch (strtoupper($params[1])) {
            case "TOPSOURCES":
                if ($type)
                    $source = new ZSourceReader($_filter["dateFrom"], $_filter["dateTo"], 7, $query, $_filter["language"], $type);
                else
                    $source = new ZSourceReader($_filter["dateFrom"], $_filter["dateTo"], 7, $query, $_filter["language"]);
                if($deviceType === 'Desktop'){
                    try {
                        //print_r($source->read());
                        $sources = $source->read();
                        $data .= "<table id=\"tableTopSources\">"
                                . "<thead><th width=\"5%\">Rank</th>"
                                . "<th width=\"40%\">Source</th>"
                                . "<th width=\"10%\">Threads</th>"
                                . "<th width=\"10%\">Mentions</th>"
                                . "<th width=\"10%\">Likes</th>"
                                . "<th width=\"10%\">Shares</th>"
                                . "<th width=\"15%\">Interaction</th>"
                                . "</thead><tbody>";
                        $index = 1;
                        foreach ($sources->getItems() as $src) {
                            $url = $src->getURL();
                            $params = explode('/', $url);
                            $title = str_replace('www.', '', $src->getSource());
                        if ($title == '')
                            ;
                        $title = str_replace('http://', '', $url);
                        $source = $src->getSource();
                        $domain = parse_url($url, PHP_URL_HOST);
                        if ($source == '')
                            $source = $domain;
                        $image = '<img src="http://www.google.com/s2/favicons?domain=' . $domain . '" style="margin-top: 8px;"/>';
                        if ($params[3] && $domain == 'www.facebook.com') {
                                $image = "<img src=\"https://graph.facebook.com/$params[3]/picture\"/>";
                            }
                        $interaction = $src->getNumberOfPosts() + $src->getNumberOfLikes() + $src->getNumberOfShares();
                            $data .= "<tr>"
                                    . "<td align=\"center\">" . $index++ . "</td>"
                                    . "<td><div style=\"float: left; margin-right: 7px; width: 32px; height: 32px; border: 1px solid #EEE; text-align: center;\">$image</div><a class=\"source-filter\" target=\"_blank\" href=\"" . $src->getURL() . "\" target=\"_blank\">" . $src->getSource() . "</a></td>"
                                    . "<td align=\"center\">" . $src->getNumberOfThreads() . "</td>"
                                    . "<td align=\"center\">" . $src->getNumberOfPosts() . "</td>"
                                    . "<td align=\"center\">" . $src->getNumberOfLikes() . "</td>"
                                    . "<td align=\"center\">" . $src->getNumberOfShares() . "</td>"
                                    . "<td align=\"center\" style=\"font-size:inherit\">" . $interaction . "</td>"
                                    . "</tr>";
                        }
                        $data .= "</tbody></table>";
                        echo $data;
                    } catch (Exception $e) {
                        echo $e->getMessage();
                    }
                }else if($deviceType === 'Mobile'){
                    try {
                        $sources = $source->read();
                        $data .= "<table id=\"tableTopSources\" class=\"dataTable\" aria-describedby=\"tableTopSources_info\">"
                                . "<thead class=\"hide\"><th width=\"5%\">Rank</th>"
                                . "<th width=\"55%\">Source</th>"
                                . "<th width=\"15%\">Posts</th>"
                                . "<th width=\"15%\">Authors</th>"
                                . "<th width=\"15%\">Threads</th></thead><tbody role=\"alert\" aria-live=\"polite\" aria-relevant=\"all\">";
                        $index = 1;
                        foreach ($sources->getItems() as $src) {
                            $url = $src->getURL();
                            $params = explode('/', $url);
                            $title = str_replace('www.', '', $src->getSource());
                            $image = '<img src="http://www.google.com/s2/favicons?domain=' . $src->getSource() . '"/>';
                            if ($params[3]) {
                                $image = "<img src=\"https://graph.facebook.com/$params[3]/picture\"/>";
                            }
                            $data .= "<tr class=\"odd\">"
                                    . "<td align=\"center\" class=\"sorting_1\">" . $index++ . "</td>"
                                    . "<td><div>".$image."</div><a class=\"source-filter\" target=\"_blank\" href=\"" . $src->getURL() . "\" target=\"_blank\">" . $title . "</a></td>"
                                    . "<td style=\"font-size:inherit\"><i class=\"ub ub-mention t-grey\"></i>" . Utils::collapseNumber($src->getNumberOfThreads()) . "</td>"
                                    . "<td><i class=\"fa fa-user t-grey\"></i>" . Utils::collapseNumber($src->getNumberOfAuthors()) . "</td>"
                                    . "<td><i class=\"fa fa-comment t-grey\"></i>" . Utils::collapseNumber($src->getNumberOfPosts()) . "</td>"
                                    . "</tr>";
                        }
                        $data .= "</tbody></table>";
                        echo $data;
                    } catch (Exception $e) {
                        echo $e->getMessage();
                    }
                }
                break;
            case "TOPAUTHORS":
                if ($type)
                    $author = new ZAuthorReader($_filter["dateFrom"], $_filter["dateTo"], 7, $query, $_filter["language"], $type);
                else
                    $author = new ZAuthorReader($_filter["dateFrom"], $_filter["dateTo"], 7, $query, $_filter["language"]);
                if($deviceType === 'Desktop'){
                    try {
                        //print_r($source->read());
                        $authors = $author->read();
                        $data .= "<table id=\"tableTopAuthors\">"
                                . "<thead><th width=\"5%\">Rank</th>"
                                . "<th width=\"35%\">Author</th>"
                                . "<th width=\"20%\">Source</th>"
                                . "<th width=\"10%\">Mentions</th>"
                                . "<th width=\"10%\">Likes</th>"
                                . "<th width=\"10%\">Shares</th>"
                                . "<th width=\"10%\">Interaction</th></thead><tbody>";
                        $index = 1;
                        foreach ($authors->getItems() as $src) {
                            $url = $src->getAuthorURL();
                            $params = explode('/', $url);
                            $title = str_replace('www.', '', $src->getSource());
                            $source = str_replace("www.", '', $src->getSource());
                            $image = '';
                            if ($title == 'tinhte.vn') {
                                $image = '<img src="http://www.google.com/s2/favicons?domain=' . $src->getSource() . '" style="margin-top: 8px;"/>';
                            } else
                                $image = '<img src="http://www.google.com/s2/favicons?domain=' . $src->getSource() . '" style="margin-top: 8px;"/>';
                            if ($params[3] + 0) {
                                $image = "<img src=\"https://graph.facebook.com/$params[3]/picture\"/>";
                            }
                            $interaction = $src->getNumberOfPosts() + $src->getNumberOfLikes();
                            $data .= "<tr>"
                                    . "<td align=\"center\">" . $index++ . "</td>"
                                    . "<td><div style=\"float: left; margin-right: 7px; width: 32px; height: 32px; border: 1px solid #EEE; text-align: center;\">$image</div><a target=\"_blank\" href=\"" . $src->getAuthorURL() . "\" target=\"_blank\">" . $src->getAuthorName() . "</a></td>"
                                    . "<td><a target=\"_blank\" href=\"http://" . $src->getSource() . "\">" . $source . "</a></td>"
                                    . "<td align=\"center\">" . $src->getNumberOfPosts() . "</td>"
                                    . "<td align=\"center\">" . $src->getNumberOfLikes() . "</td>"
                                    . "<td align=\"center\">N/A</td>"
                                    . "<td align=\"center\" style=\"font-size:inherit\">" . $interaction . "</td>"
                                    . "</tr>";
                        }
                        $data .= "</tbody></table>";
                        echo $data;
                    } catch (Exception $e) {
                        echo $e->getMessage();
                    }
                }else if($deviceType === 'Mobile'){
                    try {
                        //print_r($source->read());
                        $authors = $author->read();
                        $data .= "<table id=\"tableTopAuthors\" class=\"dataTable\" aria-describedby=\"tableTopAuthors_info\">"
                                . "<thead class=\"hide\"><th width=\"5%\">Rank</th>"
                                . "<th width=\"55%\">Author</th>"
                                . "<th width=\"15%\">Source</th>"
                                . "<th width=\"15%\">Posts</th></thead><tbody role=\"alert\" aria-live=\"polite\" aria-relevant=\"all\">";
                        $index = 1;
                        foreach ($authors->getItems() as $src) {
                            $url = $src->getAuthorURL();
                            $params = explode('/', $url);
                            $title = str_replace('www.', '', $src->getSource());
                            $source = str_replace("www.", '', $src->getSource());
                            $image = '';
                            if ($title == 'tinhte.vn') {
                                $image = '<img src="http://www.google.com/s2/favicons?domain=' . $src->getSource() . '"/>';
                            } else
                                $image = '<img src="http://www.google.com/s2/favicons?domain=' . $src->getSource() . '"/>';
                            if ($params[3] + 0) {
                                $image = "<img src=\"https://graph.facebook.com/$params[3]/picture\"/>";
                            }
                            $data .= "<tr class=\"odd\">"
                                    . "<td align=\"center\" class=\"sorting_1\">" . $index++ . "</td>"
                                    . "<td><div>$image</div><a target=\"_blank\" href=\"" . $src->getAuthorURL() . "\" target=\"_blank\">" . $src->getAuthorName() . "</a></td>"
                                    . "<td style=\"font-size:inherit\"><i class=\"fa fa-comment t-grey\"></i>" . Utils::collapseNumber($src->getNumberOfPosts()) . "</td>"
                                    . "<td class=\"large\"><a target=\"_blank\" href=\"http://" . $src->getSource() . "\">" . $source . "</a></td>"
                                    . "</tr>";
                        }
                        $data .= "</tbody></table>";
                        echo $data;
                    } catch (Exception $e) {
                        echo $e->getMessage();
                    }
                }
                break;
            case "TOPTHREADS":
                if ($type)
                    $thread = new ZThreadReader($_filter["dateFrom"], $_filter["dateTo"], 7, $query, $_filter["language"], $type);
                else
                    $thread = new ZThreadReader($_filter["dateFrom"], $_filter["dateTo"], 7, $query, $_filter["language"]);
                if($deviceType === 'Desktop'){
                    try {
                        $data .= "<table id=\"tableTopThreads\">"
                                . "<thead><th width=\"5%\">Rank</th>"
                                . "<th width=\"35%\">Thread</th>"
                                . "<th width=\"15%\">Source</th>"
                                . "<th width=\"10%\">Mentions</th>"
                                . "<th width=\"10%\">Likes</th>"
                                . "<th width=\"10%\">Shares</th>"
                                . "<th width=\"15%\">Interaction</th></thead></tbody>";
                        $index = 1;
                        $thread->read(function($item) use (&$data, &$index) {
                            $src = $item;
                            $url = $src->getThreadURL();
                            $source = str_replace("www.", '', $src->getSource());
                            $interaction = $src->getNumberOfPosts() + $src->getNumberOfTotalLikes() + $src->getNumberOfTotalShares();
                            $data .= "<tr>"
                                    . "<td align=\"center\">" . $index++ . "</td>"
                                    . "<td><a target=\"_blank\" href=\"" . $url . "\">" . $src->getThreadTitle() . "</a></td>"
                                    . "<td align=\"center\"><a target=\"_blank\" href=\"http://" . $src->getSource() . "\">" . $source . "</a></td>"
                                    . "<td align=\"center\">" . $src->getNumberOfPosts() . "</td>"
                                    . "<td align=\"center\">" . $src->getNumberOfTotalLikes() . "</td>"
                                    . "<td align=\"center\">" . $src->getNumberOfTotalShares() . "</td>"
                                    . "<td align=\"center\" style=\"font-size:inherit\">" . $interaction . "</td>"
                                    . "</tr>";
                        }, 0, 50);
                        $data .= "</tbody></table>";
                        echo $data;
                    } catch (Exception $e) {
                        echo $e->getMessage();
                    }
                } else if($deviceType === "Mobile"){
                    try {
                        $data .= "<table id=\"tableTopThreads\" class=\"dataTable\" aria-describedby=\"tableTopThreads_info\">"
                                . "<thead class=\"hide\"><th width=\"5%\">Rank</th>"
                                . "<th width=\"55%\">Thread</th>"
                                . "<th width=\"15%\">Source</th>"
                                . "<th width=\"15%\">Posts</th>"
                                . "<th width=\"15%\">Authors</th>"
                                . "<th width=\"15%\">Total Likes</th></thead><tbody role=\"alert\" aria-live=\"polite\" aria-relevant=\"all\">";
                        $index = 1;
                        $thread->read(function($item) use (&$data, &$index) {
                            $src = $item;
                            $url = $src->getThreadURL();
                            $source = str_replace("www.", '', $src->getSource());
                            $params = explode('/', $url);
                            $image = '';
                            if ($title == 'tinhte.vn') {
                                $image = '<img src="http://www.google.com/s2/favicons?domain=' . $src->getSource() . '"/>';
                            } else
                                $image = '<img src="http://www.google.com/s2/favicons?domain=' . $src->getSource() . '"/>';
                            if ($params[3] + 0) {
                                $image = "<img src=\"https://graph.facebook.com/$params[3]/picture\"/>";
                            }
                            $data .= "<tr class=\"odd thread\">"
                                    . "<td align=\"center\" class=\"sorting_1\">" . $index++ . "</td>"
                                    . "<td class=\"thread-title\"><div>$image</div><a class=\"source-filter\" target=\"_blank\" href=\"" . $url . "\" target=\"_blank\">" . $src->getThreadTitle() . "</a></td>"
                                    . "<td class=\"thread-source\"><a target=\"_blank\" href=\"http://" . $src->getSource() . "\">" . $source . "</a></td>"
                                    . "<td style=\"font-size:inherit\"><i class=\"fa fa-like t-grey\"></i>" . Utils::collapseNumber($src->getNumberOfTotalLikes()) . "</td>"
                                    . "<td><i class=\"fa fa-user t-grey\"></i>" . Utils::collapseNumber($src->getNumberOfAuthors()) . "</td>"
                                    . "<td><i class=\"fa fa-comment t-grey\"></i>" . Utils::collapseNumber($src->getNumberOfPosts()) . "</td>"
                                    . "</tr>";
                        }, 0, 50);
                        $data .= "</tbody></table>";
                        echo $data;
                    } catch (Exception $e) {
                        echo $e->getMessage();
                    }
                }
                break;
            case "MT":
                $data = array(
                    'http://localhost/ws/trendline/MTQw/%7B%22streamId%22:%22MTQw%22,%22dateFrom%22:%2203-05-2014%22,%22dateTo%22:%2213-05-2014%22,%22language%22:[%222%22],%22tags%22:[%220%22],%22type%22:[%220%22],%22source%22:[%220%22]%7D',
                    'http://localhost/ws/trendline/MTQw/%7B%22streamId%22:%22MTQw%22,%22dateFrom%22:%2203-05-2014%22,%22dateTo%22:%2213-05-2014%22,%22language%22:[%222%22],%22tags%22:[%220%22],%22type%22:[%220%22],%22source%22:[%220%22]%7D',
                    'http://localhost/ws/trendline/MTQw/%7B%22streamId%22:%22MTQw%22,%22dateFrom%22:%2203-05-2014%22,%22dateTo%22:%2213-05-2014%22,%22language%22:[%222%22],%22tags%22:[%220%22],%22type%22:[%220%22],%22source%22:[%220%22]%7D'
                );
                $r = Utils::multiRequest($data);
                echo '<pre>';
                print_r($r);
                break;
            case "COMPARESOV":
                $streamIds = array();
                $streamIds[0] = $params[2];
                $streamIdsRaw = explode(',', $params[3]);
                foreach ($streamIdsRaw as $streamId) {
                    $streamIds[] = $streamId;
                }
                $dateFrom = $params[5];
                $dateTo = $params[6];
                $language = $params[7];
                $platform = $params[8];
                $tag = $params[9];
                $sentiment = $params[10];
                $result = array();
                foreach ($streamIds as $streamId) {
                    if ($streamId == '0')
                        continue;
                    $stream = Stream::withId($streamId);
                    $filter['streamId'] = $streamId;
                    $filter['dateFrom'] = $dateFrom;
                    $filter['dateTo'] = $dateTo;
                    $filter['type'] = array($platform);
                    $filter['language'] = array($language);
                    $filter['tags'] = array($tag);
                    $filter['sentiment'] = $sentiment;
                    $filter['source'] = array('0');
                    $trend = Metrics::getTrendlineData($filter);
                    $data = array();
                    $data['date'] = array();
                    $data['data'] = array();
                    $weekData = array();
                    foreach ($trend['data'] as $key => $value) {
                        $data['date'][] = $key;
                        $data['data'][] = $value;
                        $weeks = x_week_range($key);
                        $weekData[$weeks[0] . ' - ' . $weeks[1]] += $value;
                    }
                    $re['stream']['id'] = $streamId;
                    $re['stream']['name'] = $stream->name;

                    //daily
                    $re['daily'] = $data;

                    //monthly
                    $months = array();
                    $total = 0;
                    $months['name'] = array();
                    $index = 0;
                    for ($i = 0; $i < count($data['date']); $i++) {
                        $md = new DateTime($data['date'][$i]);
                        $month = $md->format("F Y");
                        if (!in_array($month, $months['name'])) {
                            $months['name'][$index] = $month;
                            $months['data'][$index] = 0;
                            $index++;
                        }
                        $months['data'][$index - 1] += $data['data'][$i];
                    }
                    $re['monthly'] = $months;

                    //process weekly
                    $wData = array();
                    foreach ($weekData as $key => $value) {
                        $wData['date'][] = $key;
                        $wData['data'][] = $value;
                    }
                    $re['weekly'] = $wData;

                    //total
                    $totalData = array();
                    $result['total']['name'][] = $stream->name;
                    $result['total']['data'][] = array_sum($months['data']);
                    //result
                    $result[] = $re;
                }
                echo json_encode($result);
                break;
            case "COMPARETREND":
                $streamIds = array();
                $streamIds[0] = $params[2];
                $streamIdsRaw = explode(',', $params[3]);
                foreach ($streamIdsRaw as $streamId) {
                    $streamIds[] = $streamId;
                }
                $dateFrom = $params[5];
                $dateTo = $params[6];
                $language = $params[7];
                $platform = $params[8];
                $tag = $params[9];
                $sentiment = $params[10];
                $result = array();
                foreach ($streamIds as $streamId) {
                    echo str_repeat(' ', 4096);
                    ob_flush();
                    flush();
                    if ($streamId == '0')
                        continue;
                    $stream = Stream::withId($streamId);
                    $filter['streamId'] = $streamId;
                    $filter['dateFrom'] = $dateFrom;
                    $filter['dateTo'] = $dateTo;
                    $filter['type'] = array($platform);
                    $filter['language'] = array($language);
                    $filter['tags'] = array($tag);
                    $filter['sentiment'] = $sentiment;
                    $filter['source'] = array('0');
                    $trend = Metrics::getTrendlineData($filter);
                    $data = array();
                    $data['date'] = array();
                    $data['data'] = array();
                    $weekData = array();
                    foreach ($trend['data'] as $key => $value) {
                        $data['date'][] = $key;
                        $data['data'][] = $value;
                        $weeks = x_week_range($key);
                        $weekData[$weeks[0] . ' - ' . $weeks[1]] += $value;
                    }
                    $re['stream']['id'] = $streamId;
                    $re['stream']['name'] = $stream->name;
                    $re['daily'] = $data;

                    //monthly
                    $months = array();
                    $total = 0;
                    $months['name'] = array();
                    $index = 0;
                    for ($i = 0; $i < count($data['date']); $i++) {
                        $md = new DateTime($data['date'][$i]);
                        $month = $md->format("F Y");
                        if (!in_array($month, $months['name'])) {
                            $months['name'][$index] = $month;
                            $months['data'][$index] = 0;
                            $index++;
                        }
                        $months['data'][$index - 1] += $data['data'][$i];
                    }
                    $re['monthly'] = $months;
                    
                    //process weekly
                    $wData = array();
                    foreach ($weekData as $key => $value) {
                        $wData['date'][] = $key;
                        $wData['data'][] = $value;
                    }
                    $re['weekly'] = $wData;
                    
                    $result[] = $re;
                }
                echo json_encode($result);
                break;
            case "COMPARESENTIMENT":
                $streamIds = array();
                $streamIds[0] = $params[2];
                $streamIdsRaw = explode(',', $params[3]);
                foreach ($streamIdsRaw as $streamId) {
                    $streamIds[] = $streamId;
                }
                $dateFrom = $params[5];
                $dateTo = $params[6];
                $language = $params[7];
                $platform = $params[8];
                $tag = $params[9];
                $sentiment = $params[10];
                $result = array();
                foreach ($streamIds as $streamId) {
                    echo str_repeat(' ', 4096);
                    ob_flush();
                    flush();
                    if ($streamId == '0') {
                        $result[] = array();
                        continue;
                    }
                    $stream = Stream::withId($streamId);
                    $filter['streamId'] = $streamId;
                    $filter['dateFrom'] = $dateFrom;
                    $filter['dateTo'] = $dateTo;
                    $filter['type'] = array($platform);
                    $filter['language'] = array($language);
                    $filter['tags'] = array($tag);
                    $filter['sentiment'] = $sentiment;
                    $filter['source'] = array('0');
                    $data = Metrics::getSentimentData($filter);
                    $re = array();
                    $dt = array();
                    foreach ($data as $key => $value) {
                        $dt[-1] += $value[-1];
                        $dt[0] += $value[0];
                        $dt[1] += $value[1];
                        $dt[-2] += $value[-2];
                        }
                    $result[] = $dt;
                    }
                echo json_encode($result);
                break;
            case "TOPSOURCESDATA":
                if ($type !== array('0'))
                    $source = new ZSourceReader($_filter['dateFrom'], $_filter['dateTo'], 7, $query, 2, $type);
                else
                    $source = new ZSourceReader($_filter['dateFrom'], $_filter['dateTo'], 7, $query, 2);
                try {
                    //print_r($source->read());
                    $sources = $source->read();
                    $result = array();
                    foreach ($sources->getItems() as $src) {
                        $fullSource = $src->getSource();
                        $domain = parse_url($src->getUrl(), PHP_URL_HOST);
                        if ($fullSource == '')
                            $fullSource = str_replace('http://', '', $src->getUrl());
                        $shortSource = str_replace('www.', '', $fullSource);
                        $image = 'http://www.google.com/s2/favicons?domain=' . $src->getSource();
                        if ($params[3]) {
                            $image = "https://graph.facebook.com/$params[3]/picture";
                        }
                        $item = new stdClass();
                        $item->source = $fullSource;
                        $item->title = $shortSource;
                        $item->image = $image;
                        $result[] = $item;
                    }
                    echo json_encode($result);
                } catch (Exception $e) {
                    echo json_encode($e->getMessage);
                }
                break;
            case "SENTIMENT":
                echo json_encode(Metrics::getSentimentData($_filter));
                break;
            case "TRENDLINE":
                echo json_encode(Metrics::getTrendlineData($_filter));
                break;
            case "TOPSOCIALPLATFORM":
                echo json_encode(Metrics::getTopSocialPlatformsData($_filter));
                break;
            case "TOPSOCIALTREND":
                echo json_encode(Metrics::getSMTTrend($_filter));
                break;
            case "SENTIMENTBYPLATFORM":
                echo json_encode(Utils::sortPlatforms(Metrics::getSentimentByPlatforms($_filter)));
                break;
            case "SENTIMENTBYSOURCE":
                echo json_encode(Utils::sortPlatforms(Metrics::getSentimentBySources($_filter)));
                break;
            case "TAGSMETRIC":
                $tagsMetric = Tag::getMetric($_filter);
                $result = array();
                foreach ($tagsMetric as $key => $metrics) {
                    $result[$key] = Utils::sortTags($metrics);
                }
                echo json_encode($result);
                break;
            case "TAGSCOMPARISON":
                $tagsMetric = Tag::getCompetitorsMetrics($_filter);
                $result = array();
                foreach ($tagsMetric as $key => $metrics) {
                    $result[$key] = Utils::sortTags($metrics);
                }
                echo json_encode($result);
                break;
            case "MONITORING":
                $_filter = (array) json_decode(urldecode($params[2]));
                $view = $_filter['view'];
                $userid = $_filter['userId'];
                $dateFrom = $_filter['dateFrom'];
                $dateTo = $_filter['dateTo'];
                $data = '';
                if ($view == 0) {
                    $moni = Moni::reloadMoni($dateFrom, $dateTo, $userid);
                    $data .='<table id="moniList">
                                <thead>
                                <tr>
                                <th width="3%">#</th>
                                <th>Date</th>
                                <th width="10%">Total</th>
                                <th>User</th>  
                                </tr>
                                </thead>';
                    if ($moni > 0) {
                        $data .= '<tbody>';
                        $stt = 0;
                        foreach ($moni as $v) {
                            $stt++;
                            $data .= '<tr>
                                    <td style="text-align:center">' . $stt . '</td>
                                    <td style="text-align:center"><a style="font-size: 13px">' . $v->moniDateCreated->format("d M H:i") . '</a></td>';
                            if ($v->moniCount > 1000) {
                                $data .='<td bgcolor="#3ADF00" style="text-align:center"><span>' . $v->moniCount . '</span></td>';
                            } elseif ($v->moniCount > 500) {
                                $data .='<td bgcolor="#FF8000" style="text-align:center"><span>' . $v->moniCount . '</span></td>';
                            } elseif ($v->moniCount < 500) {
                                $data .='<td bgcolor="red" style="text-align:center"><span>' . $v->moniCount . '</span></td>';
                            }
                            $data .='<td style="text-align:center;font-size:inherit"><span>' . $v->moniUserFullname . '</span></td>';
                        }
                        $data .='</tbody></table>';
                    }
                } elseif ($view == 1) {
                    $moni = Moni::monthU($userid);
                    $data .='<table id="moniList">
                                <thead>
                                <tr>
                                <th width="3%">#</th>
                                <th width="20%">User</th>
                                <th width="20%">Total</th>
                                <th width="20%">Salary</th>                                             
                                </tr>
                                </thead>';
                    if ($moni > 0) {
                        $data .= '<tbody>';
                        $stt = 0;
                        foreach ($moni as $v) {
                            $stt++;
                            $data .= '<tr>
                                    <td style="text-align:center">' . $stt . '</td>
                                    <td style="text-align:center"><a style="font-size: 13px">' . $v->moniUserFullname . '</a></td>';

                            $data .='<td style="text-align:center"><span>' . $v->moniCount . '</span></td>';

                            $data .='<td style="text-align:center;font-size:inherit"><span>' . (round($v->moniCount * 400 / 3 / 1000) * 1000) . '</span></td>';
                        }
                    }
                } elseif ($view == 2) {
                    $moni = Moni::lastUpdate($userid);
                    $data .='<table id="moniList">
                                    <thead>
                                    <tr>
                                    <th width="3%">#</th>
                                    <th width="30%">User</th>
                                    <th width="20%">Last Score</th>                                    
                                    </tr>
                                    </thead>';
                    if ($moni > 0) {
                        $data .= '<tbody>';
                        $stt = 0;
                        foreach ($moni as $v) {
                            $stt++;
                            $data .= '<tr>
                                        <td style="text-align:center">' . $stt . '</td>
                                        <td style="text-align:center"><a style="font-size: 13px">' . $v->moniUserFullname . '</a></td>';
                            $data .='<td style="text-align:center;font-size:inherit"><span>' . $v->moniLast . '</span></td>';
                        }
                    }
                    $data .='</tbody></table>';
                }
                echo $data;
                break;
            case "GETOPTIONS":
                if (isset($_filter['name']) && isset($_filter['type']))
                    echo json_encode(Options::getOption($_filter['name'], $_filter['type']));
                break;
            case "CHANGEOPTIONS":
                if (isset($_filter['name']) && isset($_filter['value']) && isset($_filter['type']))
                    echo json_encode(Options::changeOption($_filter['name'], $_filter['value'], $_filter['type']));
                break;
        }
        exit(0);
        break;
    case "FBOBJECT":
        $fbUserId = $params[1];
        $fbPostId = $params[2];
        $postData = Facebook::getFacebookObjectId($fbUserId, $fbPostId);
        echo ($postData);
        return;
    case "FBIMAGE":
        $fbPostId = $params[1];
        $fbCommentId = $params[2];
        $postData = Facebook::getFacebookUserid($fbPostId, $fbCommentId);
        echo ($postData);
        return;
    case "FOLDER":
        $folderController = new FolderController(new Folder(), new FolderView());
        $folderController->render();
        include "View/".$deviceType."/Folder/FolderViewHTML.php";
        header('Content-length: ' . ob_get_length());
        return;
    case "LOGOUT":
        $userId = null;
        session_start();
        $_SESSION['switchfrom'] = '';
        $_SESSION['userid'] = null;
        session_write_close();
        echo "<script>window.location = '/'</script>";
        break;
    case "AUTHORIZETWITTER":
        if (!isset($_GET["oauth_token"])) {
            Twitter::getAuthorization($_SERVER['HTTP_HOST'] . '/authorizeTwitter');
        } else {
            if (Twitter::getCredentials() == 'true')
                echo "<script>window.close()</script>";
        }
        return;
    case "AUTHORIZEFACEBOOK":
        session_start();
        try {
            $fbId = Facebook::getUserId();

            if (!$fbId) {
                $login_url = Facebook::getLoginURL();
                header("Location: $login_url");
            } else {
                try {
                    $result = Facebook::getAuthorization();
                    session_write_close();
                    if ($result == 'true')
                        echo "<script>window.close()</script>";
                } catch (FacebookApiException $e) {
                    $login_url = Facebook::getLoginURL();
                    header("Location: $login_url");
                }
            }
        } catch (Exception $err) {
            echo $err->getMessage();
        }
        exit(0);
    case "AUTHORIZEGOOGLE":
        if (!isset($_GET["code"])) {
            $login_url = Google::getLoginURL();
            header("Location: $login_url");
        } else {
            if (Google::getAuthorization() == 'true')
                echo "<script>window.close()</script>";
        }
        return;
    case "AUTHORIZELINKEDIN":
        if (!isset($_GET["oauth_token"])) {
            LinkedIn::getAuthorization($_SERVER['HTTP_HOST'] . '/authorizeLinkedIn');
        } else {
            $t = LinkedIn::getCredentials();
            echo "<script>window.close()</script>";
        }
        return;
    case "FACEBOOKPREVIEW":
        $fbUserId = $params[1];
        $fbPostId = $params[2];
        $c = curl_init("http://graph.facebook.com/$fbUserId");
        // necessary so CURL doesn't dump the results on your page
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($c);
        curl_close($c);
        $facebookUser = json_decode($result);
        echo '<style>
                body { text-align: center; padding: 50px; }
                </style>
                <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, \'script\', \'facebook-jssdk\'));</script>
<div class="fb-post" data-href="https://www.facebook.com/' . $facebookUser->username . '/posts/' . $fbPostId . '" data-width="550"><div class="fb-xfbml-parse-ignore"></div></div>
';
        return;
    case "L":
        $linkId = $params[1];
        return;
    case "SWITCHUSER":
        include("View/".$deviceType."/User/Switch.php");
        return;
    case "MONITORING":
        if ($user->teamId != '2' && $user->type != '4' && $user->type != '3')
            return;
        $moniController = new MoniController(new Moni(), new MoniView());
        $moniController->render();
        $pageTitle = "Monitoring";
        break;
    default:
        header('HTTP/1.0 404 Not Found');
        echo "<style>
		body {background: #f9fee8;margin: 0; padding: 20px; text-align:center; font-family:Arial, Helvetica, sans-serif; font-size:14px; color:#666666;}
		.error_page {width: 600px; padding: 50px; margin: auto;}
		.error_page h1 {margin: 20px 0 0;}
		.error_page p {margin: 10px 0; padding: 0;}		
		a {color: #9caa6d; text-decoration:none;}
		a:hover {color: #9caa6d; text-decoration:underline;}
		</style><body class=\"login\">
                <div class=\"error_page\">
                  <img alt=\"Kidmondo_face_sad\" src=\"/Images/kidmondo_face_sad.gif\">
                  <h1>We're sorry...</h1>
                  <p>The page or journal you are looking for cannot be found.</p>
                  <p><a href=\"http://pulse.buzzmetrics.vn\">Return to the homepage</a></p>
                </div>

              </body>";
        exit();
        break;
}

$folderController = new FolderController(new Folder(), new FolderView());
$folderController->render();
$params[0] = strtolower($params[0]);
if (isset($params[1]))
    $params[1] = strtolower($params[1]);
$params[0] = ucfirst($params[0]);
if (isset($params[1]))
    $params[1] = ucfirst($params[1]);

//Generate View
if (strtoupper($params[0]) !== "LOGIN") {
    $masterView = MasterView::getInstance();
    $masterView->param = $params[0];
    $masterView->pageTitle = $pageTitle;
    if (strtoupper($params[0]) !== "SETTINGS") {
        if (strtoupper($params[0]) == "ACTIVITY" || strtoupper($params[0]) == "MONITORING") {
            if ($params[2] == '') {
                $params[2] = $params[1];
                if (strtoupper($params[0]) == "ACTIVITY")
                    $params[1] = 'Tasks';
                else
                    $params[1] = 'Monitoring';
            }
            $masterView->mainView = "View/".$deviceType."/$params[0]/" . $params[1] . "ViewHTML.php";
            $masterView->viewPort = "View/".$deviceType."/$params[0]/" . $params[0] . "ViewPortHTML.php";
            if (strtoupper($params[2]) == 'VIEWPORT') {
                $masterView->display("MasterViewPort.php");
            } else if (strtoupper($params[2]) == 'MAINVIEW') {
                $masterView->display("MasterMainView.php");
            } else {
                $masterView->display("MasterPage.php");
            }
        } else {
            $masterView->mainView = "View/".$deviceType."/$params[0]/" . $params[0] . "ViewHTML.php";
            $masterView->viewPort = "View/".$deviceType."/$params[0]/" . $params[0] . "ViewPortHTML.php";
            if (strtoupper($params[1]) == 'VIEWPORT') {
                $masterView->display("MasterViewPort.php");
            } else if (strtoupper($params[1]) == 'MAINVIEW') {
                $masterView->display("MasterMainView.php");
            } else {
                $masterView->display("MasterPage.php");
            }
        }
    } else {
        $masterView->mainView = "View/".$deviceType."/$params[0]/" . $params[1] . "ViewHTML.php";
        $masterView->viewPort = "View/".$deviceType."/$params[0]/" . $params[0] . "ViewPortHTML.php";
        if (strtoupper($params[2]) == 'VIEWPORT') {
            $masterView->display("MasterViewPort.php");
        } else if (strtoupper($params[2]) == 'MAINVIEW') {
            $masterView->display("MasterMainView.php");
        } else {
            $masterView->display("MasterPage.php");
        }
    }
}

header('Content-length: ' . ob_get_length());

//$masterView->display("LoginPage.php");
//$message = Message::withId(1);
#region Procedures
function getProd($data) {
    return $data;
}

function getTrendlineData($_filter) {
    return mineServer::getTrendlineData($_filter);
}

function getTopSocialPlatformsData($_filter) {
    return mineServer::getTopSocialPlatformsData($_filter);
}

function getSharingMetricsData($_filter) {
    return mineServer::getSharingMetricsData($_filter);
}

function getSentimentData($_filter) {
    return Metrics::getSentimentData($_filter);
}

function getGenderDistributionData($_filter) {
    return mineServer::getGenderDistributionData($_filter);
}

function getTopLanguagesData($_filter) {
    return mineServer::getTopLanguagesData($_filter);
}

function getGeographicDistributionData($_filter) {
    return mineServer::getGeographicDistributionData($_filter);
}

function getExposureData($_filter) {
    return mineServer::getExposureData($_filter);
}

function getConversationMapData($_filter) {
    return mineServer::getConversationMapData($_filter);
}

function saveStream($stream) {
    return (array) mineServer::saveStream($stream);
}

function addTask($userId, $taskType, $taskDescription, $assignedTo, $messageId, $streamId, $post, $department) {
    return (array) mineServer::addTask($userId, $taskType, $taskDescription, $assignedTo, $messageId, $streamId, $post, $department);
}

function markComplete($id, $action) {
    return mineServer::markComplete($id, $action);
}

function undoComplete($id) {
    return mineServer::undoComplete($id);
}

function deleteTask($id) {
    return mineServer::deleteTask($id);
}

function getLogin($login) {
    return mineServer::getLogin($login);
}

function getUser() {
    return mineServer::getUser();
}

function addUser($user) {
    return mineServer::addUser($user);
}

function getFolder() {
    return mineServer::getFolder();
}

function addFolder($folderName, $folderId) {
    return mineServer::addFolder($folderName, $folderId);
}

function listUser() {
    return mineServer::listUser();
}

function listStream($folderid) {
    return mineServer::listStream($folderid);
}

function getFolderId($name) {
    return mineServer::getFolderId($name);
}

function getFolderType() {
    return mineServer::getFolderType();
}

function addTag($messageId, $tagId, $streamId) {
    return mineServer::addTag($messageId, $tagId, $streamId);
}

function deleteUser($userid) {
    return mineServer::deleteUser($userid);
}

function getTag() {
    return mineServer::getTag();
}

function createTag($tagName, $keyword, $groupId) {
    return mineServer::createTag($tagName, $keyword, $groupId);
}

function deleteTag($tagid) {
    return mineServer::deleteTag($tagid);
}

function getNameZone($timezone) {
    return mineServer::getTimeZone($timezone);
}

function getTimeZone($name, $location) {
    return mineServer::getTimeZone($name, $location);
}

function getInfo() {
    return mineServer::getInfo();
}

function deleteStream($streamId) {
    return mineServer::deleteStream($streamId);
}

function getStream($streamId) {
    return mineServer::getStream($streamId);
}

function getLogedInUser() {
    return mineServer::getLogedInUser();
}

function changePassword($oldPassword, $newPassword) {
    return mineServer::changePassword($oldPassword, $newPassword);
}

function changeName($name) {
    return mineServer::changeName($name);
}

function changeSentiment($messageId, $threadId, $score, $datecreated, $streamId, $type, $source) {
    return mineServer::changeSentiment($messageId, $threadId, $score, $datecreated, $streamId, $type, $source);
}

function postTweet($mesageId, $streamId, $message) {
    return mineServer::postTweet($mesageId, $streamId, $message);
}

function getTwitters() {
    return mineServer::getTwitters();
}

function deleteTwitter($twitterid) {
    return mineServer::deleteTwitter($twitterid);
}

function deleteFacebook($facebookid) {
    return mineServer::deleteFacebook($facebookid);
}

function getFacebooks() {
    return mineServer::getFacebooks();
}

function postFacebookStatus($mesageId, $streamId, $message, $link) {
    return mineServer::postFacebookStatus($mesageId, $streamId, $message, $link);
}

function deleteFolder($folderId) {
    return mineServer::deleteFolder($folderId);
}

function getGoogles() {
    return mineServer::getGoogles();
}

function deleteGoogle($googleid) {
    return mineServer::deleteGoogle($googleid);
}

function deleteLinkedIn($linkedinid) {
    return mineServer::deleteLinkedIn($linkedinid);
}

function getLinkedIns() {
    return mineServer::getLinkedIns();
}

function postLinkedInStatus($message) {
    return mineServer::postLinkedInStatus($message);
}

function getAccounts() {
    return mineServer::getAccounts();
}

function getSpikes($filter) {
    return mineServer::getSpikes($filter);
}

function getURL($url) {
    return mineServer::getURL($url);
}

function removeTag($tagId, $streamId, $messageId) {
    return mineServer::removeTag($tagId, $streamId, $messageId);
}

function addMessageAction($messageActionType, $messageId, $threadId, $streamId) {
    return mineServer::addMessageAction($messageActionType, $messageId, $threadId, $streamId);
}

function markAsSpam($messageId, $threadId, $streamId, $source, $author) {
    return mineServer::markAsSpam($messageId, $threadId, $streamId, $source, $author);
}

function getReplies($threadId, $streamId, $dateFrom, $dateTo, $index = 0, $length = 5) {
    return mineServer::getReplies($threadId, $streamId, $dateFrom, $dateTo, $index, $length);
}

function shareEmail($sendTo, $subject, $content) {
    return mineServer::shareEmail($sendTo, $subject, $content);
}

function comment($fbPostID, $message) {
    return mineServer::comment($fbPostID, $message);
}

function markAsRead($streamId, $threadId, $messageId) {
    return mineServer::markAsRead($streamId, $threadId, $messageId);
}

function addTagofTask($taskId, $tagId) {
    return mineServer::addTagofTask($taskId, $tagId);
}

function removeTagofTask($taskId, $tagId) {
    return mineServer::removeTagofTask($taskId, $tagId);
}

function markForSendingLater($messageId, $streamId, $post, $action) {
    return mineServer::markForSendingLater($messageId, $streamId, $post, $action);
}

function sendSMSNow($taskId, $phoneNumber, $text) {
    return mineServer::sendSMSNow($taskId, $phoneNumber, $text);
}

function sendSMSToQueue($messageId, $streamId, $post, $action) {
    return mineServer::sendSMSToQueue($messageId, $streamId, $post, $action);
}

function getMailHTML($taskIds) {
    return mineServer::getMailHTML($taskIds);
}

function sendSMS($phoneNumber, $message) {
    return mineServer::sendSMS($phoneNumber, $message);
}

function getTagMetric($streamId) {
    return mineServer::getTagMetric($streamId);
}

function getTopSources($filter) {
    return mineServer::getTopSources($filter);
}

function saveComparison($id, $name, $streamId1, $streamId2) {
    return mineServer::saveComparison($id, $name, $streamId1, $streamId2);
}

function getGroups() {
    return mineServer::getGroups();
}

function listTag($groupId) {
    return mineServer::listTag($groupId);
}

function addTagGroup($groupName) {
    return mineServer::addTagGroup($groupName);
}

function modifyTag($tagId, $tagName, $keywords, $groupId) {
    return mineServer::modifyTag($tagId, $tagName, $keywords, $groupId);
}

function modifyGroup($groupId, $groupName) {
    return mineServer::modifyGroup($groupId, $groupName);
}

function deleteGroup($groupId) {
    return mineServer::deleteGroup($groupId);
}

function getSentimentByPlatforms($filter) {
    return mineServer::getSentimentByPlatforms($filter);
}

function getSentimentBySources($filter) {
    return mineServer::getSentimentBySources($filter);
}

function x_week_range($date) {
    $ts = strtotime($date);
    $start = strtotime('last monday', $ts);
    if (strtotime('this monday', $ts) == $ts)
        $start = strtotime('this monday', $ts);
    $end = strtotime('next sunday', $ts);
    if (strtotime('this sunday', $ts) == $ts)
        $end = strtotime('this sunday', $ts);
    return array(date('M d', $start),
        date('M d', $end));
}

function getHostInfo($host) {
    return mineServer::getHostInfo($host);
}

?>